<?php
/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class ApiController extends CController
{
	CONST APPLICATION_ID = 'ASCCPE';

	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
			array('allow',
				'actions' => array('*'),
				'users' => array('?')
			),
		);
	}
	
	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError() {
		if ($error = Yii::app()->errorHandler->error) {
			$this->_sendError($error['message'], $error['code']);
		}
	}
	
	protected function _sendResponse($data=null, $code=200) {
		header('Content-type: application/json');
		$resp = array('code'=>$code);
		if ($data!==null) {
			$resp['data'] = $data;
		}
		
		echo json_encode($resp);
		Yii::app()->end();
	}
	
	protected function _sendError($errors, $code=500) {
		$this->_sendResponse($errors, $code);
	}

	protected function _sendSuccess($data, $code=200) {
		$this->_sendResponse($data, $code);
	}
}